package com.wb.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;

import java.util.*;

public class SelfZuulFilter extends ZuulFilter {

    private final Logger logger = LoggerFactory.getLogger(SelfZuulFilter.class);

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication instanceof OAuth2Authentication)) {
            return null;
        }
        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) authentication;
        Authentication userAuthentication = oAuth2Authentication.getUserAuthentication();
        List<String> authorities = new ArrayList<>();
        userAuthentication.getAuthorities().stream().forEach(s -> authorities.add(((GrantedAuthority) s).getAuthority()));
        OAuth2Request oAuth2Request = oAuth2Authentication.getOAuth2Request();

        Map<String,String> requestParametes = oAuth2Request.getRequestParameters();
        Map<String,Object> jsonToken = new HashMap<>(requestParametes);
        if (userAuthentication != null) {
            jsonToken.put("principal", userAuthentication.getName());
            jsonToken.put("authorities", authorities);
        }
        ObjectMapper objectMapper = new ObjectMapper();
        Enumeration<String> enumeration;
        try {
            enumeration = currentContext.getRequest().getHeaderNames();
            while (enumeration.hasMoreElements()) {
                logger.info(" ------------------ 之前 header : {} " , enumeration.nextElement());
            }
            currentContext.addZuulRequestHeader("json-token", objectMapper.writeValueAsString(jsonToken));
            enumeration = currentContext.getRequest().getHeaderNames();
            while (enumeration.hasMoreElements()) {
                logger.info(" ------------------ 之后 header : {} " , enumeration.nextElement());
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
